package com.base.test;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
public class FolderZipCompressor {
 
    public static void zipFolder(String folderPath, String zipFilePath) throws IOException {
        File folder = new File(folderPath);
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);
 
        addFolderToZip("", folder, zos);
        zos.close();
        fos.close();
    }
 
    private static void addFolderToZip(String path, File folder, ZipOutputStream zos) throws IOException {
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                addFolderToZip(path + "/" + file.getName(), file, zos);
            } else {
                byte[] buffer = new byte[1024];
                FileInputStream fis = new FileInputStream(file);
                zos.putNextEntry(new ZipEntry(path + "/" + file.getName()));
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }
                zos.closeEntry();
                fis.close();
            }
        }
    }
 
    public static void main(String[] args) {
        try {
            zipFolder("/path/to/folder", "/path/to/output.zip");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}